package proyecto.testcasetool.tests;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import org.eclipse.emf.ecore.xmi.impl.XMIResourceImpl;
import org.junit.BeforeClass;
import org.junit.Test;

import proyecto.testcasetool.UseCaseModel;
import testcasetool.transformation.algorithm.Ad2TestCase;
import testcasetool.transformation.algorithm.Uc2AdTransformation;
import testcasetool.transformation.presentation.ActivityDiagramViewer;
import testcasetool.transformation.presentation.TestCaseHtmlViewer;
import testcasetool.transformation.presentation.TestCaseViewer;
import testcasetool.transformation.uml.activity.Activity;
import testcasetool.transformation.uml.utp.TestCase_TestCase;

public class PruebaTransformacion {

	private static UseCaseModel ucModel;
	
	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
		XMIResourceImpl resource = new XMIResourceImpl();
		File source = new File("src/proyecto/testcasetool/tests/My.testcasetool");
		resource.load( new FileInputStream(source), new HashMap<Object,Object>());
		ucModel = (UseCaseModel) resource.getContents().get(0);
	}

	@Test
	public void test() {
		System.out.println(ucModel.getSubject().getName());
		
		Activity ad = Uc2AdTransformation.generateActivityDiagram(ucModel.getSubject().getUseCase().get(0));
		
		ActivityDiagramViewer adw = new ActivityDiagramViewer();
		adw.printAD(ad);
		
		List<TestCase_TestCase> testCases = Ad2TestCase.generateTestCases(ad);
		for (TestCase_TestCase tc : testCases) {
			TestCaseViewer.printTestCase(tc);
		}
		
		
	}
	
	@Test
	public void testGenerateHTML() {
		Activity ad = Uc2AdTransformation.generateActivityDiagram(ucModel.getSubject().getUseCase().get(0));
		
		List<TestCase_TestCase> testCases = Ad2TestCase.generateTestCases(ad);
		StringBuffer sb = new StringBuffer();
		sb.append("<html><body><h1>Casos de Prueba para <i>" + ucModel.getSubject().getUseCase().get(0).getName() + "</i></h1>");
		for (TestCase_TestCase tc : testCases) {
			sb.append(TestCaseHtmlViewer.generateHtmlTestCase(tc));
			sb.append("<HR />\n");
		}
		sb.append("</body></html>");
		writeTextFile("tests.html", sb.toString());
	}
	
	public void writeTextFile(String fileName, String s) {
		FileWriter output = null;
		BufferedWriter writer = null;
		try {
			output = new FileWriter(fileName);
			writer = new BufferedWriter(output);
			writer.write(s,0, s.length());
			writer.flush();
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		} finally {
			if (output != null) {
				try {
					output.close();
				} catch (IOException e) {
					// Ignore issues during closing
				}
			}
			if (writer != null) {
				try {
					writer.close();
				} catch (IOException e) {
					//Ignore issues during closing;
				}
			}
		}

	  } 

}
